package de.stefanocke.roo.wicket.templates

import de.stefanocke.roo.wicket.Stereotypes

class AnnotationUtilsTemplate extends JavaHtmlTemplate{
	
	override String javaClassNameWhenNew(){
		"AnnotationUtils"
	}

	override String stereotype(){
		Stereotypes::ANNOTATION_UTILS
	}
	
	override subPackageToUseWhenNew(){
		"common"
	}
	
	override buildJavaContents(){
		import_("java.lang.annotation.Annotation")
		import_("java.util.HashMap")
		import_("java.util.Map")
		'''
		«stereotypeAnnotation»
		public class «simpleTypeName» {
			«stereotypeAnnotation(Stereotypes::ANNOTATION_UTILS_GET_ANNOTATIONS)»
			public static AnnotationMap getAnnotations(Class<?> modelClass,
					Class<?> fieldsClass, String fieldName, String modelClassFieldName) {
				try {
					Map<Class<? extends Annotation>, Annotation> map = new HashMap<Class<? extends Annotation>, Annotation>();
					Annotation[] annotations = fieldsClass.getDeclaredField(fieldName).getAnnotations();
					for (int i = 0; i < annotations.length; i++) {
						map.put(annotations[i].annotationType(), annotations[i]);
					}
		
					if (modelClassFieldName != null) {
						annotations = modelClass.getDeclaredField(modelClassFieldName).getAnnotations();
						for (int i = 0; i < annotations.length; i++) {
							if (!map.containsKey(annotations[i].annotationType())) {
								map.put(annotations[i].annotationType(), annotations[i]);
							}
						}
					}
					return new AnnotationMap(map);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
			
			public static class AnnotationMap{
				private Map<Class<? extends Annotation>, Annotation> map;
		
				private AnnotationMap(Map<Class<? extends Annotation>, Annotation> map) {
					this.map = new HashMap<Class<? extends Annotation>, Annotation>(map);
				}
				
				@SuppressWarnings("unchecked")
				public <A extends Annotation> A get(Class<? extends A> annotationClass){
					return (A) map.get(annotationClass);
				}
			}
		}
		'''
	}
	
	
}